import smtplib
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from common.config_utils import config

class EmailUtils():
    def __init__(self,email_body,email_attach_path=None):
        self.server=config.Server
        self.sender=config.Sender
        self.resiver=config.Resiver
        self.password=config.Password
        self.cc=config.CC
        self.subjct=config.Subject
        self.email_text=email_body
        self.html_report_path=email_attach_path
    def email_body(self):
        emaile_text=MIMEText(self.email_text,'html','utf-8')
        email_obj=MIMEMultipart()
        email_obj.attach( emaile_text)
        email_obj['from']=self.sender
        email_obj['to']=self.resiver
        email_obj['Cc']=self.cc
        email_obj['subject']=self.subjct
        if self.html_report_path:
            attach_file=MIMEText( open(self.html_report_path,'rb').read(),'base64','utf-8')
            attach_file['Content-type']='application/octet-stream'
            attach_file.add_header('Content-Disposition','attachment',filename=('gbk','',os.path.basename(self.html_report_path)))
            email_obj.attach( attach_file )
        return email_obj
    def send_email(self):
        smtp=smtplib.SMTP()
        smtp.connect(self.server)
        smtp.login(user=self.sender,password=self.password)
        smtp.sendmail(self.sender,self.resiver.split(','),self.email_body().as_string())
        smtp.close()

# if __name__ == '__main__':
#     email_body = '''
#     <h1 align="center">接口自动化测试报告 </h1>
#     <p align="center">详情请见附件</p>
#     '''
#     report_path = os.path.join(os.path.dirname(__file__), '..', 'html_reports', 'WX_TEST_API_V1.9',
#                                'WX_TEST_API_V1.9.html')
#     email_obj=EmailUtils(email_body,report_path)
#     email_obj.send_email()